# -*- coding:utf-8 -*-
"""
@Time : 2022/4/27 5:24 PM
@Author: xiaomi
@Des: 用户管理
"""
from app.common.common import write_access_log
from core.Response import success, fail, res_antd
from models.base import Ad
from schemas.backend import ad
from core.Auth import create_access_token, check_permissions
from fastapi import Request, Query, APIRouter, Security, File, UploadFile
from config import settings
from typing import List
from tortoise.queryset import F

router = APIRouter(prefix='')


@router.post("", summary="新增广告", dependencies=[Security(check_permissions, scopes=["ad_add"])])
async def ad_add(post: ad.CreateAd):
    """
    新增广告
    :param post: CreateAd
    :return:
    """
    # 创建广告
    create_ad = await Ad.create(**post.model_dump())
    if not create_ad:
        return fail(msg=f"创建失败!")
    return success(msg=f"创建成功")


@router.delete("", summary="删除广告", dependencies=[Security(check_permissions, scopes=["ad_delete"])])
async def ad_del(post: ad.DeleteAd):
    """
    删除广告
    :param req:
    :param key: List[int]
    :return:
    """
    delete_action = await Ad.filter(pk__in=post.key).delete()
    if not delete_action:
        return fail(msg=f"删除失败!")
    return success(msg="删除成功")


@router.put("", summary="广告修改", dependencies=[Security(check_permissions, scopes=["ad_update"])])
async def ad_update(post: ad.UpdateAd):
    """
    更新用户信息
    :param post:
    :return:
    """
    ad_check = await Ad.get_or_none(pk=post.id)
    # 超级管理员或不存在的用户
    if not ad_check:
        return fail(msg="广告不存在")
    
    data = post.model_dump()
    data.pop("id")
    await Ad.filter(pk=post.id).update(**data)
    return success(msg="更新成功!")


@router.get("",
            summary="广告列表",
            response_model=ad.AdListData,
            dependencies=[Security(check_permissions, scopes=["ad_query"])]
            )
async def ad_list():
    """
    获取所有广告
    :return:
    """
    # 查询条件
    query = {}
    ad_data = Ad.annotate(key=F("id")).all()
    # 总数
    total = await ad_data.count()
    # 查询
    data = await ad_data.order_by("-create_time").values(
        "key", "id", "title", "sort", "status", "create_time", "update_time")

    return success(code=200, data=data)